package com.pulsar.service.impl;

import com.pulsar.dao.UserDao;
import com.pulsar.entity.User;
import com.pulsar.entity.vo.LoginVo;
import com.pulsar.handler.GlobalException;
import com.pulsar.message.ResponseCode;
import com.pulsar.redis.RedisClient;
import com.pulsar.redis.key.UserKey;
import com.pulsar.service.UserService;
import com.pulsar.util.ConsUtil;
import com.pulsar.util.MD5Util;
import com.pulsar.util.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述: <br>
 * 所属包名: com.pulsar.service.impl<br>
 * 创建人　: 白剑<br>
 * 创建时间: 2018/07/30 19:39:06<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    RedisClient redisClient;

    @Override
    public User getUserById(long userId) {
        return userDao.getUserById(userId);
    }

    @Override
    public User getByToken(HttpServletResponse response, String token) {

        if (StringUtils.isEmpty(token)) {
            return null;
        }

        User user = redisClient.get(UserKey.token, token, User.class);

        // 提取token说明用户访问，这是需要重置session失效时间，对于redis，重新设置下key值即可
        if (user != null) {
            addCookie(response, token, user);
        }

        return user;
    }

    @Override
    public boolean login(HttpServletResponse response, LoginVo loginVo) {

        if (loginVo == null) {
            throw new GlobalException(ResponseCode.SERVER_ERROR);
        }

        String mobile = loginVo.getMobile();
        String formPass = loginVo.getPassword();

        // 判断手机号是否存在
        User user = getUserById(Long.parseLong(mobile));
        if (user == null) {
            throw new GlobalException(ResponseCode.MOBILE_NOT_EXIST);
        }

        // 验证密码
        String dbPass = user.getUserPassword();
        String saltDB = user.getPassMix();
        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
        if (!calcPass.equals(dbPass)) {
            throw new GlobalException(ResponseCode.PASSWORD_ERROR);
        }

        // 生成cookie
        String token = UUIDUtil.uuid();
        addCookie(response, token, user);

        return true;
    }

    private void addCookie(HttpServletResponse response, String token, User user) {
        redisClient.set(UserKey.token, token, user);
        Cookie cookie = new Cookie(ConsUtil.COOKI_NAME_OF_TOKEN, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }

}
